package com.hopu.iocdemo1;

import java.lang.reflect.Field;

/**
 * 电脑工厂
 */
public class ComputerFactory {

    /**
     * 创建电脑
     * @return
     */
    public Computer createComputer() throws NoSuchFieldException, IllegalAccessException, InstantiationException {
        //获得Computer的类型
        Class clazz = Computer.class;
        //创建Compuer对象
        Object computer = clazz.newInstance();
        //获得cpu和memory属性
        Field cpu = clazz.getDeclaredField("cpu");
        //读取属性上的注解
        ComputerComponent cpuCom = cpu.getDeclaredAnnotation(ComputerComponent.class);
        //读取注解中的type
        Class cpuClass = cpuCom.type();
        //创建cpu对象配置到cpu属性上
        Object cpuObj = cpuClass.newInstance();
        cpu.setAccessible(true);
        //通过Computer对象调用属性实现赋值
        cpu.set(computer,cpuObj);

        Field memory = clazz.getDeclaredField("memory");
        ComputerComponent memoryCom = memory.getDeclaredAnnotation(ComputerComponent.class);
        Class memoryClass = memoryCom.type();
        Object memoryObj = memoryClass.newInstance();
        memory.setAccessible(true);
        memory.set(computer,memoryObj);
        return (Computer) computer;
    }
}
